import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Subscription } from 'rxjs';
import { Observable } from 'rxjs';
import {
  productDelete,
  productSelected,
  productSelectedAll,
} from 'src/app/shared/ngrx/cart-store/cart.action';
import { CartItem } from 'src/app/shared/ngrx/cart-store/cart.reducer';
import { getStateSlice } from 'src/app/shared/ngrx/cart-store/cart.selector';
import { UtilsService } from 'src/app/shared/service/utils.service';

@Component({
  selector: 'app-recommend-container',
  templateUrl: './recommend-container.component.html',
  styleUrls: ['./recommend-container.component.less'],
})
export class RecommendContainerComponent implements OnInit {
  cart$!: Observable<CartItem[]>;
  allSelectedIsTrue: boolean = false;
  subCart$!: Subscription;
  constructor(private store: Store, private utils: UtilsService) {}

  ngOnInit() {
    this.cart$ = this.getCartList();
    this.subCart$ = this.cart$.subscribe((data) => {
      let products = this.utils.deepClone(data);
      if (products.length !== 0) {
        this.allSelectedIsTrue = products.every(
          (item: any) => item.selected === true
        );
      } else {
        this.allSelectedIsTrue = false;
      }
    });
  }
  getCartList() {
    return this.store.select(getStateSlice());
  }
  handleDeleteProductClick(index: number) {
    this.store.dispatch(productDelete({ index }));
  }
  handleSelect(product: any) {
    let productClone = this.utils.deepClone(product);
    productClone.selected = !productClone.selected;
    this.store.dispatch(productSelected({ productSelect: productClone }));
  }
  handleSelectAll() {
    let cartList: any = [];
    this.cart$
      .subscribe((data) => {
        let products = this.utils.deepClone(data);
        this.allSelectedIsTrue = products.every(
          (item: any) => item.selected === false
        );
        products.map((item: any) => {
          if (this.allSelectedIsTrue) {
            item.selected = true;
          } else {
            item.selected = false;
          }
          return item;
        });
        cartList = products;
      })
      .unsubscribe();
    this.store.dispatch(productSelectedAll({ selectAll: cartList }));
  }
}
